package com.example.backend.controller;

import com.example.backend.domain.entity.Feedback;
import com.example.backend.domain.entity.Ticket;
import com.example.backend.domain.entity.User;
import com.example.backend.dto.FeedbackDto;
import com.example.backend.mapper.SimpleMappers;
import com.example.backend.service.FeedbackService;
import com.example.backend.service.TicketService;
import com.example.backend.service.UserService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/feedbacks")
public class FeedbackController {
    private final FeedbackService feedbackService;
    private final TicketService ticketService;
    private final UserService userService;

    public FeedbackController(FeedbackService feedbackService, TicketService ticketService, UserService userService) {
        this.feedbackService = feedbackService;
        this.ticketService = ticketService;
        this.userService = userService;
    }

    public record CreateFeedbackRequest(Long ticketId,
                                        Long authorId,
                                        @NotBlank @Size(max = 2000) String content,
                                        @Min(1) @Max(5) Integer rating) {}

    @PostMapping
    public ResponseEntity<FeedbackDto> create(@Valid @RequestBody CreateFeedbackRequest req) {
        Ticket ticket = ticketService.findById(req.ticketId()).orElseThrow();
        User author = userService.findById(req.authorId()).orElseThrow();
        Feedback feedback = Feedback.builder()
                .ticket(ticket)
                .author(author)
                .content(req.content())
                .rating(req.rating())
                .build();
        Feedback saved = feedbackService.save(feedback);
        return ResponseEntity.ok(SimpleMappers.toFeedbackDto(saved));
    }

    @GetMapping("/ticket/{ticketId}")
    public ResponseEntity<Page<FeedbackDto>> listByTicket(@PathVariable Long ticketId, Pageable pageable) {
        Page<FeedbackDto> page = feedbackService.findByTicket(ticketId, pageable).map(SimpleMappers::toFeedbackDto);
        return ResponseEntity.ok(page);
    }
}


